<template>
  <div class="login_box">
    <a-form 
      :model="loginForm" 
      name="basic" 
      autocomplete="off" 
      @finish="onFinish" 
      @finishFailed="onFinishFailed"
      layout="horizontal" 
      ref="formRef"
    >
      <a-form-item label="账号" name="username" :rules="[{ required: true, message: '请输入账号' }]">
        <a-input v-model:value="loginForm.username" placeholder="请输入账号" size="large" />
      </a-form-item>
      <a-form-item label="密码" name="password" :rules="[{ required: true, message: '请输入密码' }]">
        <a-input-password v-model:value="loginForm.password" placeholder="请输入密码" size="large" />
      </a-form-item>
      <a-form-item label="邮箱" name="email" :rules="[{ required: true, message: '请输入邮箱' }]">
        <a-input v-model:value="loginForm.email" placeholder="请输入邮箱" size="large" />
      </a-form-item>
      <a-form-item label="邮箱验证码" name="email_code" :rules="[{ required: true, message: '请输入邮箱验证码' }]">
        <a-input v-model:value="loginForm.email_code" placeholder="请输入邮箱验证码" size="large">
          <template #suffix>
            <a-button type="dashed" :disabled="getCodeDisabled" @click="getEmailCode">{{ emailState }}</a-button>
          </template>
        </a-input>
      </a-form-item>
      <a-form-item label="手机号" name="mobile" :rules="[{ required: true, message: '请输入您的手机号' }]">
        <a-input v-model:value="loginForm.mobile" placeholder="请输入您的手机号" size="large" />
      </a-form-item>
      <a-form-item label="验证码" name="img_code" :rules="[{ required: true, message: '请输入验证码' }]">
        <a-input v-model:value="loginForm.img_code" placeholder="请输入验证码" size="large">
          <template #suffix>
            <img-code ref="imgCodev"></img-code>
          </template>
        </a-input>
      </a-form-item>
      <slot></slot>
      <a-form-item>
        <div class="submin_btn_box">
          <a-button type="primary" html-type="submit" size="large" :block="true">注册</a-button>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { message } from "ant-design-vue";
import type { FormInstance } from 'ant-design-vue';
import { getCodeImg } from "@/api/public/index";
import { getEmail, useRegister } from "@/api/user";
import imgCode from "@/components/imgCode/index.vue";

const router = useRouter();
const imgCodev = ref<any>(null);

interface LoginForm {
  username: string;
  password: string;
  email: string;
  email_code: string;
  mobile: string;
  img_code: string;
}

const getCodeDisabled = ref<boolean>(false);
const loginForm = reactive<LoginForm>({
  username: "",
  password: "",
  email: "",
  email_code: "",
  mobile: "",
  img_code: ""
});

const formRef = ref<FormInstance>();
const codeImg = ref("https://hzh.woide.top/com/image");
const emailState = ref<string>("获取验证码");
const emailTimer = ref<number | null>(null);
const timerValue = ref<number>(60);

const successRegister = defineEmits(['successRegister']);

const getEmailCode = async () => {
  if (formRef.value) {
    try {
      await formRef.value.validateFields(["email"]);
      const res = await getEmail({ email: loginForm.email });
      if (res.data.code !== 0) {
        return message.error({ content: res.data.msg });
      }
      message.success({ content: res.data.msg });
      getCodeDisabled.value = true;
      startEmailCountdown();
    } catch (err) {
      console.error(err);
    }
  }
};

const startEmailCountdown = () => {
  emailState.value = `${timerValue.value}秒后重新获取`;
  emailTimer.value = setInterval(() => {
    if (timerValue.value > 0) {
      timerValue.value -= 1;
      emailState.value = `${timerValue.value}秒后重新获取`;
    } else {
      clearInterval(emailTimer.value!);
      emailState.value = "获取验证码";
      getCodeDisabled.value = false;
      timerValue.value = 60;
    }
  }, 1000);
};

const getNewCodeImg = async () => {
  const res = await getCodeImg();
  if (res.data.code === 200) {
    codeImg.value = `https://hzh.woide.top/com/image?${Math.floor(Math.random() * 100000)}`;
  } else {
    message.error({ content: res.data.msg });
  }
};

const key = "加载中…………";
const onFinish = async (values: any) => {
  message.loading({ content: "Loading...", key, duration: 2 });
  const res = await useRegister({
    nickname: "",
    username: loginForm.username,
    password: loginForm.password,
    email: loginForm.email,
    email_code: loginForm.email_code,
    mobile: loginForm.mobile,
    image_code: loginForm.img_code,
    sharecode: router.currentRoute.value.query.sharecode || '',
  });
  if (res.data.code !== 0) {
    message.error({ content: res.data.msg });
    imgCodev.value.getNewCodeImg();
    return;
  }
  message.success({ content: res.data.msg });
  successRegister('successRegister');
  
};

const onFinishFailed = (errorInfo: any) => {
  message.loading({ content: "Loading...", key });
  setTimeout(() => {
    message.error({ content: "注册失败!", key, duration: 2 });
  }, 1000);
};
</script>

<style lang="scss" scoped>
.submin_btn_box {
  text-align: center;
  margin: 0 auto;
  margin-top: 20px;
  width: 80%;
}
</style>
